class ManagerusersController < ApplicationController
  # GET /managerusers
  # GET /managerusers.json
  before_filter :authenticate_user!
  def index
    if session[:user].role != "admin"
      redirect_to homepage_url
    else
      @users = User.all
      @profiles=@users.map{|x| x.user_profile}
      respond_to do |format|
        format.html # index.html.erb
        format.json { render json: @managerusers }
      end
    end
  end

  # GET /managerusers/1
  # GET /managerusers/1.json
  def show
    if session[:user].role != "admin"
      redirect_to homepage_url
    else
      @user = User.find(params[:id])
      @profile= @user.user_profile
      respond_to do |format|
        format.html # show.html.erb
        format.json { render json: @manageruser }
      end
    end
  end

  # GET /managerusers/new
  # GET /managerusers/new.json
  def new
    if session[:user].role != "admin"
      redirect_to homepage_url
    else
      @user = User.new
      @user_profile= UserProfile.new
      @manageruser= Manageruser.new
      respond_to do |format|
        format.html {notice}
        format.json { render json: @manageruser }
      end
    end
  end

  # GET /managerusers/1/edit
  def edit
    if session[:user].role != "admin"
      redirect_to homepage_url
    else
      @user = User.find(params[:id])
      @user_profile=@user.user_profile
    end
  end

  # POST /managerusers
  # POST /managerusers.json
  def create
    if session[:user].role != "admin"
      redirect_to homepage_url
    else
      uploaded_io = params[:manageruser][:excel_file]
      tmp = uploaded_io.tempfile

      file = File.join("public","uploads",Date.today.to_s+"_"+uploaded_io.original_filename)
      FileUtils.cp tmp.path, file
      require 'spreadsheet'
      book = Spreadsheet.open(tmp)
      sheet1 = book.worksheet(0) # can use an index or worksheet name
      rowstt=0
      haserror=false

      log=File.new("public\\log\\log"+Date.today.to_s+".txt",File::CREAT|File::TRUNC|File::RDWR, 0644)
      sheet1.each do |row|
        if rowstt>0
          break if row[0].nil? # if first cell empty
          username=row[1]
          email=row[2]
          mssv=row[3]
          role="member"
          puts row
          #errorcode=validate(username,email,mssv)
          line=""

          reg1=/[a-zA-Z0-9_\.]+/
          if !(username.to_s =~ reg1)
            line=line+"username"
          end

          if ! /[\w]+@[\w]+(\.[\w]+)+/.match(email.to_s)
            if line!=""
              line=line+", email"
            else
              line=line+"email"
            end
          end

          if !/[a-zA-Z0-9]{8}/.match(mssv.to_s)
            if line!=""
              line=line+", mssv"
            else
              line=line+"mssv"
            end
          end

          if line!=""
            line=line+" is INVALID.\n"
          end
          puts "line: "+line
          if line != ""
            haserror=true
            log.write("record "+rowstt.to_s+". "+line)
          log.flush
          else
          #no error invalid
            line=""
            if User.find_by_username(username)==nil
              #user exits will be skip
              if User.find_by_email(email)!=nil
                if line==""
                  line=line+"email"
                else
                  line=line+", email"
                end
              end
              if UserProfile.find_by_mssv(mssv.to_s)!=nil
                if line==""
                  line=line+"mssv"
                else
                  line=line+", mssv"
                end
              end
              if line!=""
                line= "Duplicate "+line+".\n"
              end
              if line!=""
                haserror=true
                log.write("record "+rowstt.to_s+". "+line)
              log.flush
              else
                addUser(username,email,mssv,role)
              end
            end
          end
        end
        rowstt+=1
      end
      log.close

      if haserror
        send_file "public\\log\\log"+Date.today.to_s+".txt",:type => "text/plain"
      #redirect_to new_manageruser_url, notice:"Has some error, please view in log file." and return
      else
        redirect_to managerusers_url, notice: 'Add all user succedd.'
      end
    end
  end

  def addUser(username,email,mssv,role)

    #print error

    generated_password = Devise.friendly_token.first(6)
    user= User.new(:username=>username,:email=>email,:password => generated_password,:role=>role)

    if user.save
      else
      puts user.errors[0]
    end
    puts "add succedd"
    profile= UserProfile.new(:mssv=> mssv.to_s)
    profile.user_id=user.id
    if profile.save

      else
      puts profile.errors[0]
    end
    UserMailer.welcome_email(username, generated_password, email).deliver
  end

  # PUT /managerusers/1
  # PUT /managerusers/1.json
  def update
    if session[:user].role != "admin"
      redirect_to homepage_url
    else
      @user_profile= UserProfile.find(params[:id])
      @user = User.find(profile.user_id)

      respond_to do |format|
        if @user.update_atrributes(params[:user_profile])
          if @user_profile.update_attributes(params[:user_profile])
            format.html { redirect_to @user_profile, notice: 'User was successfully updated.' }
            format.json { head :no_content }
          else
            format.html { render action: "edit" }
            format.json { render json: @user_profile.errors, status: :unprocessable_entity }
          end
        else
          format.html { render action: "edit" }
          format.json { render json: @user_profile.errors, status: :unprocessable_entity }
        end
      end
    end
  end

  # DELETE /managerusers/1
  # DELETE /managerusers/1.json
  def destroy
    if session[:user].role != "admin"
      redirect_to homepage_url
    else
      listdelete=params[:userdelete]
      puts params[:userdelete]
      listdelete.each do |e|
        @user= User.find(e)
        @user.destroy
      end
      # @user = User.find(params[:id])
      #@user.destroy

      respond_to do |format|
        format.html { redirect_to managerusers_url }
        format.json { head :no_content }
      end
    end
  end
end
